import React, {Component, PropTypes} from 'react';
import { connect } from 'react-redux';
import {messages, checkMenuDisabled, deepFullCopy} from "share/common";
import errorMessage from "share/errorMessage";
import { Icon, message, Switch, Tag, Button, Modal, Input, Form, Popconfirm } from 'antd';
import NewExpense from "../../../my-account/new-expense";
import SlideFrame from "components/slide-frame";
import Condition from "components/condition";
import QuickReply from "components/template/quick-reply";
import baseService from "share/base.service";
import autoAuditService from "../../../finance-setting/auto-audit/auto-audit.service";
import expenseReportService from "../../../expense-report/expense-report.service";
import financeAuditService from "../../new-finance-audit/finance-audit.service";
import "styles/financial-management/innvoice-bag-approve/audit-expense-detail.scss";
import ModalDeleteConfirm from "../../new-finance-audit/components/modal-delete-confirm";

const { If } = Condition;
const { TextArea } = Input;
const FormItem = Form.Item;

@Form.create()
class AuditExpenseDetail extends Component {

  state = {
    loading: false,
    rejectLoading: false,
    nowExpense: {}, // 费用详情
    auditEditable: !!this.props.auditEditable, //财务审核时，费用是否为编辑状态
    costCenterItemsApportion: [],
    manualAuditLoading: false,
    info: this.props.info || {}, // 报销单详情
    jobInfo: this.props.jobInfo || {}, // 岗位信息
    isWaitForAudit: this.props.isWaitForAudit,
    isAuditEditable: this.props.isAuditEditable,
    showRejectModal: false,
    attachmentOIDs: [],
    invoiceList: this.props.invoiceList || [], // 报销单下的费用列表
    showExpenseReportInvoices: deepFullCopy(this.props.showExpenseReportInvoices)
  };

  static contextTypes = {
    entry: PropTypes.string,
    readOnly: PropTypes.bool,
    form: PropTypes.object
  };

  componentDidMount() {
    this.getInfo(this.props);
    this.getDetail(this.props);
  }

  componentWillReceiveProps(nextProps) {
    let { nowExpense } = this.state;
    if (nowExpense.invoiceOID !== nextProps.record.invoiceOID) {
      this.setState({ nowExpense: {} });
      this.getInfo(nextProps);
      this.getDetail(nextProps);
    }
  }

  // 报销单详情／岗位信息／费用列表
  getInfo = props => {
    const { record: { expenseReportOID }, options: { auditBaseConfig } } = props;
    let { info } = this.props;
    if (info && info.expenseReportOID) {
      this.getCostCenterItems();
      return;
    }
    expenseReportOID && Promise.all([
      expenseReportService.getExpenseReportDetail(expenseReportOID),
      expenseReportService.getAuditChain(expenseReportOID, 1002),
      expenseReportService.getExpenseAccountInfo({ expenseReportOID, isDateCombinedUTC: false })
    ]).then(res => {
      let expenseReport = res[0].data.rows;
      let chainInfo = res[1].data;
      expenseReport.applicantJobId && expenseReportService.getJobInfo(expenseReport.applicantJobId).then(response => {
        this.setState({
          jobInfo: response.data || {}
        })
      })
      let isAuditInApproveStatus = chainInfo.chainDTO && chainInfo.chainDTO.currentFlag && chainInfo.chainDTO.nodeType === 1012;
      let isWaitForAudit = this.checkNewAuth() && ((expenseReport.status === 1003 && chainInfo.prendingAudit) || isAuditInApproveStatus);
      let isAuditEditable = isWaitForAudit && auditBaseConfig.reviewEditSuitable && auditBaseConfig.reviewEditEnable;
      this.setState({
        info: expenseReport,
        isWaitForAudit,
        isAuditEditable,
        invoiceList: res[2].data && res[2].data.rows ? res[2].data.rows.expenseReportInvoices || [] : []
      }, this.getCostCenterItems);
    })
  };

  // 费用详情
  getDetail = props => {
    const { record: { invoiceOID } } = props;
    this.setState({ loading: true });
    invoiceOID && baseService.getInvoiceDetail(invoiceOID).then(res => {
      this.setState({
        loading: false,
        nowExpense: res.data
      })
    })
  };

  getCostCenterItems = () => {
    const { info: { custFormValues } } = this.state;
    let costCenterItemsApportion = [];
    //查询是否多币种、初始化成本中心项
    custFormValues && custFormValues.map(field => {
      if (field.messageKey === 'select_cost_center') {
        if (JSON.parse(field.fieldConstraint || '{}').isApportionItem) { //参与分摊
          costCenterItemsApportion.push({
            fieldName: field.fieldName,
            costCenterOID: JSON.parse(field.dataSource || '{}').costCenterOID,
            costCenterItemName: field.showValue,
            name: field.showValue,
            costCenterItemOID: field.value,
            required: field.required
          })
        }
      }
      if (field.messageKey === 'select_department') {
        if (JSON.parse(field.fieldConstraint || '{}').isApportionItem) { //参与分摊
          costCenterItemsApportion.push({
            fieldName: field.fieldName,
            costCenterOID: '00000000-0000-0000-0000-000000000000',
            costCenterItemName: field.showValue,
            name: field.showValue,
            costCenterItemOID: field.value,
            required: field.required
          })
        }
      }
    });
    this.setState({ costCenterItemsApportion });
  };

  // 人工审核标记
  handleManualAudit = checked => {
    let { nowExpense, info: { expenseReportOID } } = this.state;
    let params = {
      invoiceOIDs: [nowExpense.invoiceOID],
      expenseReportOID,
      manualAudit: checked
    };
    this.setState({ manualAuditLoading: true });
    autoAuditService.setManualAudit(params).then(() => {
      nowExpense.manualAudit = checked;
      this.setState({ manualAuditLoading: false, nowExpense });
      message.success(messages('common.operate.success')/*操作成功*/);
    }).catch(e => {
      this.setState({ manualAuditLoading: false });
      errorMessage(e.response);
    })
  };

  renderTitle = () => {
    const { loading, auditEditable, manualAuditLoading, nowExpense, isAuditEditable, isWaitForAudit, info } = this.state;
    const { changeInvoiceEnable } = this.props;
    const { form } = this.context;
    let manualAudit = nowExpense && nowExpense.manualAudit;
    let manualAuditText = manualAudit ? messages('expense-15.key26')/*已审核*/ :
      messages('expense-15.key27')/*待审核*/;
    return (
      <div>
        {messages('expense-15.key28')/*费用详情*/}
        <If value={auditEditable && manualAudit}>
          <Tag color="#DFEAFF" className="audit-expense-detail-manual-tag">{manualAuditText}</Tag>
        </If>
        <If value={!loading}>
          <div className="audit-expense-detail-buttons">
            <If value={isWaitForAudit && !auditEditable && !info.corporateFlag}>
              <span className="audit-expense-detail-buttons-switch">
                <Switch
                  size="small"
                  checked={!!manualAudit}
                  loading={manualAuditLoading}
                  onChange={this.handleManualAudit}
                />
                {manualAuditText}
              </span>
            </If>
            <If value={isAuditEditable && !auditEditable}>
              <a onClick={() => this.setState({ auditEditable: true })}>
                <Icon type="form" /> {messages('common.edit')/*编辑*/}
              </a>
            </If>
            <If value={changeInvoiceEnable && !auditEditable && !info.corporateFlag}>
              <a onClick={() => this.setState({ auditEditable: true })}>
                <Icon type="form" /> {messages('expense-15.key186')/*换票*/}
              </a>
            </If>
          </div>
        </If>
      </div>
    )
  };

  onClose = value => {
    this.setState({ auditEditable: false, nowExpense: {} });
    this.props.close(value && value.refresh, value && value.rejectAll);
  };

  renderMoreBtn = () => {
    const { options: { auditBaseConfig }, isShowNewBotton } = this.props;
    const { auditEditable, info, nowExpense } = this.state;
    let moreButtons = [];
    if (
      !this.context.readOnly &&
      !checkMenuDisabled() &&
      auditBaseConfig.reviewEditSuitable &&
      auditBaseConfig.expenseBatchReject &&
      !auditEditable &&
      [1002, 1003].includes(info.status) &&
      nowExpense.expenseTypeSubsidyType !== 1
    ) {
      moreButtons.push(
        <Button
          className="audit-expense-detail-reject-btn"
          onClick={() => this.setState({ showRejectModal: true })}
        >
          {messages('expense-15.key29')/*驳回费用*/}
        </Button>
      );
    }

    if (!isShowNewBotton || this.context.entry === 'view') {
      return moreButtons;
    }
    if (this.props.profile['new.web.page.switch.enable.tmp'])
      moreButtons.push(
        <Button
          type={'primary'}
          onClick={this.props.handleSwitchNew}
        >
          {messages('expense-15.key30')/*切换新版*/}
        </Button>);
    return moreButtons;
  };

  handleImageUpload = attachments => {
    this.setState({ attachmentOIDs: attachments.map(a => a.attachmentOID) })
  };

  // 费用驳回
  handleReject = () => {
    const { invoiceList, info } = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (invoiceList.length === 1) {
          ModalDeleteConfirm.open({
            visible: true,
            info,
            onOk: deleteBagRelation => this.confirmReject(values.reason, deleteBagRelation)
          })
        } else {
          this.confirmReject(values.reason, false)
        }
      }
    })
  };

  confirmReject = (reason, deleteBagRelation) => {
    const { setFieldsValue } = this.props.form;
    const { record: { invoiceOID } } = this.props;
    const { attachmentOIDs, invoiceList, info: { expenseReportOID } } = this.state;
    let params = {
      approvalTxt: reason,
      expenseReportOID,
      invoiceOIDs: [invoiceOID],
      needChargeBack: false,
      attachmentOIDs,
      deleteBagRelation
    };
    this.setState({ rejectLoading: true });
    financeAuditService.rejectExpense(params).then(res => {
      let { failReason, successNum, failNum } = res.data;
      this.setState({ rejectLoading: false });
      setFieldsValue({ reason: '' });
      this.quickReplyRef && this.quickReplyRef.clearData();
      if (res.status === 200 && failNum === 0) {
        this.setState({ showRejectModal: false });
        message.success(messages('common.operate.success')/*操作成功*/);
        this.onClose({ refresh: true, rejectAll: invoiceList.length === 1 });
      } else {
        let firstError = failReason[Object.keys(failReason)[0]];
        message.error(`${messages('common.operate.filed')/*操作失败*/}, ${firstError}`)
      }
    }).catch(e => {
      this.setState({ rejectLoading: false });
    });
  }

  cancelReject = () => {
    // this.quickReplyRef && this.quickReplyRef.clearData();
    this.setState({ showRejectModal: false })
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { visible, switchingInvoice, record, annotateOnChange,
      changeInvoiceEnable
    } = this.props;
    const { info, jobInfo, auditEditable, costCenterItemsApportion, nowExpense, isWaitForAudit, isAuditEditable,
      showRejectModal, rejectLoading, showExpenseReportInvoices } = this.state;
    return (
      <div className="audit-expense-detail">
        <SlideFrame
          show={visible}
          title={this.renderTitle()}
          content={NewExpense}
          hasFooter={false}
          onClose={this.onClose}
          afterClose={this.onClose}
          params={{
            isFinance: true,
            tab: 'prending_audit',
            slideFrameShowFlag: visible,
            isWithTime: info.withTime,
            expenseReport: info,
            readOnly: true,
            hasInit: false,
            audit: true,
            nowExpense,
            jobInfo,
            auditEditable,
            isWaitForAudit,
            isAuditEditable,
            costCenterItemsApportion,
            showExpenseReportInvoices,
            switchingInvoice,
            moreBottomButtons: this.renderMoreBtn(),
            annotateOnChange,
            changeInvoiceEnable,
            // fix bug 55413
            onChangeShowExpenseReportInvoices: invoices => this.setState({ showExpenseReportInvoices: invoices })
          }}
        />

        <Modal
          visible={showRejectModal}
          confirmLoading={rejectLoading}
          title={messages('expense-15.key29')/*驳回费用*/}
          okText={messages('common.reject')/*驳回*/}
          onOk={this.handleReject}
          onCancel={this.cancelReject}
        >
          <FormItem>
            {getFieldDecorator('reason', {
              rules: [{
                required: true,
                message: messages('expense-15.key32')/*请输入temp2*/
              }, {
                max: 500,
                message: messages('common.max.characters.length',{arg1: 500})/*最多输入{arg1}个字符*/
              }]
            })(
              <QuickReply
                onRef={ref => this.quickReplyRef = ref}
                handleImageUpload={this.handleImageUpload}
                params={{
                  audit: true,
                  withAttachments: true,
                  applicantOID: record.applicantOID
                }}
              >
                <TextArea
                  placeholder={messages('expense-15.key33')/*请填写驳回理由*/}
                  rows={5}
                  style={{ resize: 'none' }}
                />
              </QuickReply>
            )}
          </FormItem>
        </Modal>
      </div>
    )
  }
}

let mapStateToProps = state => {
  return {
    options: state.login.options,
    profile: state.login.profile,

  }
};

export default connect(mapStateToProps)(AuditExpenseDetail);
